<?php
/**
 * @desc 微信.交易查询
 * @document https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_2&index=4
 * @author Vincent
 */

namespace young\payment;

use young\Common;

class WxRefund extends WxConfig
{

    public function run($data)
    {
        $this->setConfig($data['config']);
        return $this->handle($data['order_sn'], $data['refund_amount'], $data['refund_sn'], $data['total_amount']);
    }

    /**
     * @param $orderSn 商户订单号
     * @param $refundAmount 退款金额
     * @param $refundSn 退款单号
     * @param $totalAmount 订单总金额
     * @return array
     * @throws \Exception
     */
    public function handle($orderSn, $refundAmount, $refundSn, $totalAmount)
    {
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
        $common = [];
        $common['appid'] = $this->appid;
        $common['mch_id'] = $this->mch_id;
        $common['nonce_str'] = Common::rand_string(32);
        $common['sign_type'] = self::SIGN_TYPE;
        $common['out_trade_no'] = $orderSn;
        $common['out_refund_no'] = $refundSn;
        $common['total_fee'] = $this->formatAmount($totalAmount);
        $common['refund_fee'] = $this->formatAmount($refundAmount);
        $common['sign'] = $this->sign($common);

        $xml = Common::arrayToXml($common);
        $result = $this->request_post($url, $xml);
        $data = Common::xmlToArray($result);
        if ($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {
            return true;
        } else {
            throw new \Exception('[err_code:' . $data['err_code'] . '][merr_code_dessg:' . $data['err_code_des'] . ']');
        }
    }
}